package com.qf.service.impl;

import com.qf.dao.TbCartDetailDao;
import com.qf.entity.TbCart;
import com.qf.dao.TbCartDao;
import com.qf.entity.TbCartDetail;
import com.qf.entity.TbInfoDetail;
import com.qf.service.TbCartService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * (TbCart)表服务实现类
 *
 * @author makejava
 * @since 2021-04-06 09:44:32
 */
@Service("tbCartService")
public class TbCartServiceImpl implements TbCartService {
    @Resource
    private TbCartDao tbCartDao;

    @Resource
    private TbCartDetailDao tbCartDetailDao;

    /**
     * 通过ID查询单条数据
     *
     * @param cartId 主键
     * @return 实例对象
     */
    @Override
    public TbCart queryById(Integer cartId) {
        return this.tbCartDao.queryById(cartId);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<TbCart> queryAllByLimit(int offset, int limit) {
        return this.tbCartDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param tbCart 实例对象
     * @return 实例对象
     */
    @Override
    public TbCart insert(TbCart tbCart) {
        this.tbCartDao.insert(tbCart);
        return tbCart;
    }

    /**
     * 修改数据
     *
     * @param tbCart 实例对象
     * @return 实例对象
     */
    @Override
    public TbCart update(TbCart tbCart) {
        this.tbCartDao.update(tbCart);
        return this.queryById(tbCart.getCartId());
    }

    /**
     * 通过主键删除数据
     *
     * @param cartId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer cartId) {
        return this.tbCartDao.deleteById(cartId) > 0;
    }

    @Override
    @Transactional
    public int insertCart(String arr) {
        String[] arrs = arr.split(",");
        int goodPrice = Integer.parseInt(arrs[arrs.length-1]);
        int userId = Integer.parseInt(arrs[arrs.length-2]);
        int goodId = Integer.parseInt(arrs[arrs.length-3]);
        TbCart tbCart = new TbCart();
        tbCart.setFkCartUserId(userId);
        tbCart.setFkCartGoodId(goodId);
        tbCart.setCartGoodPrice(goodPrice);
        tbCartDao.insertCart(tbCart);
//        System.out.println(tbCartDao.insertCart(tbCart));

        System.out.println(tbCart.getCartId());
        List<TbCartDetail> cartDetailList = new ArrayList<>();
        for (int i = 0 ; i < arrs.length - 3 ; i ++) {
            TbCartDetail tbCartDetail = new TbCartDetail();
            tbCartDetail.setFkCartId(tbCart.getCartId());
            tbCartDetail.setFkInfoDetailId(Integer.parseInt(arrs[i]));
            cartDetailList.add(tbCartDetail);
        }
        int i = tbCartDetailDao.insertBatch(cartDetailList);
        return i;
    }
}